const {
  getStudentInformation,
  updateStudentInformation,
  getStudentList,
  getCoachStudentListById, newStudent, delStudent
} = require('../controller/student')
const {newAccount, deleteAccountByUsername} = require("../controller/user");
const Response = require('../common/Response')
const router = require('koa-router')()

router.prefix('/api/student')

// 获取所有学员信息
router.get('/list', async (context, next) => {
  const rows = await getStudentList()
  context.body = Response.success(rows)
});
// 添加学员，创建默认账户
router.post('/new', async (context, next) => {
  const StudentValue = await newStudent(context.request.body.student)
  if (StudentValue) {
    const UserValue = await newAccount(context.request.body.account)
    if (UserValue) {
      context.body = Response.success('添加学员成功')
    }
  } else {
    context.body = Response.failure('添加学员失败')
  }
})
// 修改学员
router.post('/update', async (context, next) => {
  const val = await updateStudentInformation(context.request.body)
  if (val) {
    context.body = Response.success('修改学员信息成功')
  } else {
    context.body = Response.failure('修改学员信息成功')
  }
})
// 删除学员，同时删除账户
router.post('/del/:id', async (context, next) => {
  const StudentValue = await delStudent(context.params.id)
  if (StudentValue) {
    const UserValue = await deleteAccountByUsername(context.request.body.identify)
    if (UserValue) {
      context.body = Response.success('删除学员成功')
    }
  } else {
    context.body = Response.failure('删除学员失败')
  }
})
// 获取学员详细信息
router.post('/detail', async (context, next) => {
  const row = await getStudentInformation(context.session.username)
  if (row.identify) {
    context.body = Response.success(row)
  } else {
    context.body = Response.failure('获取学员信息失败')
  }
})
// 根据教练 id === coach_id 获取学员信息
router.post('/list/:id', async (context, next) => {
  const rows = await getCoachStudentListById(context.params.id)
  context.body = Response.success(rows)
});

module.exports = router;
